import Taro, {} from '@tarojs/taro'
import { View,Canvas, Button } from '@tarojs/components'
import { useRef } from 'react';
import { getUpToken } from '@/api';
import { useRequest, useSetState } from 'ahooks';
import { Buffer } from 'buffer';

import './vipam.module.scss'
import SignatureCanvas  from 'react-signature-canvas'

import {SignaturePad} from "@yz1311/taro-signature-pad";
import html2canvas from 'html2canvas'

export default function Vipam() {
    const [params, setParams] = useSetState({
        token: '',
        asset_id: '',
        url: '',
        key: '',
        signature: null
    }); 

    const signRef = useRef(null);
    console.log('this',signRef)

    // let upToken = '';

    const { data: { data: { } = {} } = {} } = useRequest(getUpToken, {
        onSuccess: (res) => {
        //   console.log(res.data);
        //   upToken = res?.data?.token;
            setParams({
                token: res?.data?.token,
                asset_id: res?.data?.asset_id,
                url: res?.data?.fileurl,
                key: res?.data?.key,
            });
        }
    });

    const clear = async () => {
        signRef.current.clear();
    };

    const save = async () => {
        // signRef.current.clear();
        if (signRef.current.isEmpty()) {
            Taro.showToast({ title: '请先签名', icon: 'none' })
            return;
        }

        // console.log(params);
        Taro.showLoading({ title: '提交中...', mask: true });

        const key64 = Buffer.from(params.key).toString('base64');

        Taro.request({
            url: 'https://up-z2.qiniup.com/putb64/-1/key/' + key64,
            method: 'POST',
            data: signRef.current.toDataURL().split('base64,')[1],
            header: {
                'Content-Type': 'application/octet-stream',
                'Authorization': "UpToken " + params.token
            },
            success: async (resp) => {
                // if (res.data.key) {
                //     console.log(res.data.key);
                // }
                console.log(resp);

                Taro.hideLoading();

                await Taro.showToast({ title: '保存成功', icon: 'none' });

                Taro.eventCenter.trigger('signed', params);

                Taro.navigateBack();
            }
        });
        
    };
  const handleTouchStart = (event) => {
    const info = event.touches[0]
    const ctx = Taro.createCanvasContext('signatureCanvas')
    ctx.beginPath()
    ctx.setStrokeStyle('#000000')
    ctx.setLineWidth(1)
    console.log('info',info)
    console.log('handleTouchStart',info)
    ctx.moveTo(info.pageX, info.pageY/3)
    
    ctx.stroke()
    ctx.draw(true)
  }
 
  const handleTouchMove = (event) => {
    const { pageX, pageY } = event.touches[0]
    console.log('handleTouchMove',pageX,pageY,this)
    const ctx = Taro.createCanvasContext('signatureCanvas')
    ctx.setStrokeStyle('#000000')
    ctx.setLineWidth(1)
    ctx.lineTo(pageX, pageY/3)
    ctx.stroke()
    ctx.draw(true)
  }
  const clearCavas= (event) =>{
    const ctx = Taro.createCanvasContext('signatureCanvas')
  }
 
  // 生成图片并转换为base64
  const generateSignature = async () => {
    try {
        Taro.canvasToTempFilePath({
            success(res) {
                console.log(res.tempFilePath)
              }
        })
    //   const canvas = await html2canvas(document.getElementById('signatureCanvas'));
    //   const dataURL = canvas.toDataURL('image/png');
    //   console.error('生成图片成功:', dataURL);
    //   setParams({ signature: dataURL });
    } catch (error) {
      console.error('生成图片失败:', error);
    }
  }
 
    return (
        <View style={{overflow:'hidden'}}>
            <View className='tip'>请在空白的地方签名</View>
            {/* <SignaturePad
                className='signature-canvas' ref={signRef} /> */}
             <SignatureCanvas  penColor="black" // 签名线条颜色
          canvasProps={{
            className: 'signature-canvas',
            height: 400,
            width: 400,
          }}  ref={signRef}/>
            <view className='flex align-center padding justify-around'>
                <Button className='line-red round cu-btn flex-sub lg' onClick={clear}>清空</Button>
                <Button className='bg-red round cu-btn lg flex-sub margin-left' style={{marginTop: 0}} onClick={save}>提交签名</Button>
            </view>
             {/* <Canvas
                className='signature-canvas'
                canvasId="signatureCanvas"
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                /> */}
               
            {/* <view className='flex align-center padding justify-around'>
                <Button className='line-red round cu-btn flex-sub lg' onClick={clearCavas}>清空</Button>
                <Button className='bg-red round cu-btn lg flex-sub margin-left' onClick={generateSignature}>提交签名</Button>
            </view> */}
        </View>
    )
}
